#include "processlog.h"
#include "channel.h"
#include "snetwork/NluConnection.h"
#include "snetwork/NluEvent.h"
#include "snetwork/NluList.h"
#include "snetwork/WorkerProcess.h"
#include "snetwork/MasterProcess.h"
#include "standard/MyPool.h"

pthread_mutex_t master_mutex;
pthread_mutex_t worker_mutex[THREAD_MAX];
pthread_t s_tid[THREAD_MAX];//线程ID
unsigned int s_thread_para[THREAD_MAX][2];
bool if_sigsegv;
#define MAX_PROC 5

namespace Sock
{   
    bool is_createchild = false;
    bool is_killchild   = false;
    int the_proc_num    = 0;
        
    CWorkerProcess *CWorkerProcess::m_instance = NULL;

    CWorkerProcess *CWorkerProcess::instance()
    {
        if (m_instance==NULL) {
            m_instance = new CWorkerProcess();
        }
        return m_instance;
    }       
    
    CWorkerProcess::CWorkerProcess()
    {
        Sock::n_request_header.erase();
        Sock::n_response_header.erase();        
        Sock::n_response_body.erase();

        for (unsigned int i=0; i<MAX_FD_NUM; i++) {
            Sock::n_fd_arr[i] = 0;
            n_clientip_arr[i] = NULL;
            n_clientport_arr[i] = 80;
        }
    }           

    void CWorkerProcess::WorkerProcessCycle(nlu_cycle_t *cycle)
    {
        vecStr fieldArr;
        std::vector<int>::iterator vect;
        http_channel_t ch;
                
        n_response_header = n_header;
        /*
        fieldArr.clear();                                       
        paramArr param;
        param.dbname = the_db_name;   
        */                     
                
        try {
            // start event listen port , init epoll
            int epfd = CNluEvent::instance()->handleInit(cycle); 
                                
            // connect mysql 
            MYSQL* mysql_conn = DbMysql::instance()->connect(the_db_name);        

            //main loop
            for ( ; ; ) {
            
                if (DbMysql::instance()->MysqlPing(mysql_conn) != 0) {
                    mysql_conn = DbMysql::instance()->connect(the_db_name); 
                }
                            
                if (http_terminate) {
                    llog("child process %d exit succeed!", getpid());
                    http_terminate = 0;
			        exit(0);
			    }
			
			    if (http_quit) {
			        llog("child process %d exit succeed!", getpid());
			        http_quit = 0;			        
			        exit(0);
			    }
			    
                CNluEvent::instance()->execute(cycle);
            }
            
            //close mysql
		    DbMysql::instance()->close(mysql_conn);            
            close(epfd);
            
            //close
            if (n_clientfd>0) {
	            close(n_clientfd);
			}
        }
        catch (CThrowException e) {
            llog("Error: %s", e.getMessage().c_str());
        }
    }                  
}
